﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using pbvs.Models;
using pbvs.Data;
using System;
using pbvs.Services.Interfaces;
using pbvs.Models.DomainModels;

namespace pbvs.Controllers
{
    public class ContentController : Controller
    {
        //
        // GET: /Content/
        private readonly IContentService _svc;

        public ContentController(IContentService svc)
        {
            _svc = svc;
        }

        public ActionResult ViewContent(string pageName)
        {
            ViewBag.pageName = pageName;
            return View();
        }

        [ChildActionOnly]
        public ActionResult PartialContentView(string pageName)
        {
            return PartialView(_svc.GetPage(pageName));
        }

        public ActionResult Edit(int id)
        {

            using (PbvsContext db = new PbvsContext())
            {
                List<ContentPage> pages = db.ContentPages.Where(m => m.Title != "").ToList();
                List<SelectListItem> contentPages = new List<SelectListItem>();
                foreach (ContentPage pg in pages)
                {
                    SelectListItem item = new SelectListItem();
                    item.Text = pg.Title;
                    item.Value = pg.Id.ToString();
                    contentPages.Add(item);
                }
                contentPages.Insert(0, new SelectListItem() { Value = "0" });
                ViewBag.contentPages = new SelectList(contentPages, "Value", "Text");
                ContentPage page = id > 0 ? db.ContentPages.Find(id)
                    : new ContentPage();
                return View(page);
            }
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(ContentPageDomainModel page)
        {
            return RedirectToAction("Edit", new { id = _svc.EditPage(page).Id });
        }
    }
}
